﻿using System.Configuration;
using System.Data.Linq;
using System.Linq;

namespace InvoiceInvoker.Logic.Repositories
{
	public class RegisteredSellerRepository : InvoiceInvoker.Logic.RepositoryInterfaces.IRegisteredSellerRepository
	{
		private string _connectionString;

		public RegisteredSellerRepository()
		{
			_connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
		}

		public int GetIdByUserName(string userName)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				return dataContext.RegisteredSellers.SingleOrDefault(seller => seller.UserName == userName).Id;
			}
		}

		public RegisteredSeller GetById(int id)
		{
			DataLoadOptions loadOptions = new DataLoadOptions();
			loadOptions.LoadWith<RegisteredSeller>(x => x.Invoices);
			loadOptions.LoadWith<RegisteredSeller>(x => x.InvoicePatterns);
			loadOptions.LoadWith<RegisteredSeller>(x => x.RegisteredCustomers);
			loadOptions.LoadWith<RegisteredSeller>(x => x.RegisteredProducts);

			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				dataContext.LoadOptions = loadOptions;
				return dataContext.RegisteredSellers.SingleOrDefault(seller => seller.Id == id);
			}
		}

		public void Add(RegisteredSeller item)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				dataContext.RegisteredSellers.InsertOnSubmit(item);
				dataContext.SubmitChanges();
			}
		}

		public void Remove(int itemId)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				var query = from seller in dataContext.RegisteredSellers where seller.Id == itemId select seller;
				dataContext.RegisteredSellers.DeleteOnSubmit(query.SingleOrDefault());
				dataContext.SubmitChanges();
			}
		}

		public void Update(RegisteredSeller item)
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				dataContext.RegisteredSellers.Attach(item, GetById(item.Id));
				dataContext.SubmitChanges();
			}
		}

		#region methods for testing

		public int GetRegisteredSellersNumber()
		{
			using (MainDataContext dataContext = new MainDataContext(_connectionString))
			{
				return dataContext.RegisteredSellers.Count();
			}
		}

		#endregion
	}
}
